/**
 * 测试1339接口标准请求格式
 * 验证分页参数和响应格式是否符合标准
 */

const WebSocket = require('ws');

class Code1339StandardFormatTester {
  constructor() {
    this.ws = null;
    this.testResults = [];
  }

  async connect () {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket('ws://localhost:3001/user-service/websocket');

      this.ws.on('open', () => {
        console.log('✅ WebSocket连接已建立');
        resolve();
      });

      this.ws.on('error', (error) => {
        console.error('❌ WebSocket连接失败:', error);
        reject(error);
      });

      this.ws.on('close', () => {
        console.log('🔌 WebSocket连接已关闭');
      });
    });
  }

  addTestResult (testName, success, message) {
    this.testResults.push({ testName, success, message });
    const status = success ? '✅' : '❌';
    console.log(`${status} ${testName}: ${message}`);
  }

  async testStandardRequestFormat () {
    console.log('\n🎯 测试1339接口标准请求格式');
    console.log('='.repeat(50));

    // 测试1: 标准请求格式 - pageNum从0开始
    await this.testPageNumZero();

    // 测试2: 分页参数验证
    await this.testPaginationParameters();

    // 测试3: 响应格式验证
    await this.testResponseFormat();

    // 测试4: 分页大小验证（默认20条）
    await this.testPageSize();

    console.log('\n📊 测试结果汇总:');
    console.log('='.repeat(50));
    this.testResults.forEach(result => {
      const status = result.success ? '✅' : '❌';
      console.log(`${status} ${result.testName}: ${result.message}`);
    });

    const successCount = this.testResults.filter(r => r.success).length;
    const totalCount = this.testResults.length;
    console.log(`\n🎉 测试完成: ${successCount}/${totalCount} 通过`);
  }

  async testPageNumZero () {
    console.log('\n📄 测试1: 标准请求格式 - pageNum从0开始');

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());

          if (message.act_id === 1339) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            // 验证响应格式
            if (message.code === 0 && Array.isArray(message.list)) {
              this.addTestResult('标准请求格式', true, 'pageNum=0请求成功，返回正确格式');
            } else {
              this.addTestResult('标准请求格式', false, `响应格式错误: ${JSON.stringify(message)}`);
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 解析响应失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('标准请求格式', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      // 发送标准格式请求
      const requestData = {
        c: 1339,
        d: { pageNum: 0 }
      };

      console.log(`📤 发送标准请求:`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      // 设置超时
      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('标准请求格式', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  async testPaginationParameters () {
    console.log('\n📄 测试2: 分页参数验证');

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());

          if (message.act_id === 1339) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            // 验证分页参数
            if (message.code === 0) {
              this.addTestResult('分页参数验证', true, 'pageNum=1请求成功');
            } else {
              this.addTestResult('分页参数验证', false, `请求失败: ${message.msg || '未知错误'}`);
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 解析响应失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('分页参数验证', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      // 测试pageNum=1
      const requestData = {
        c: 1339,
        d: { pageNum: 1 }
      };

      console.log(`📤 发送分页请求:`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      // 设置超时
      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('分页参数验证', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  async testResponseFormat () {
    console.log('\n📄 测试3: 响应格式验证');

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());

          if (message.act_id === 1339) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            // 验证响应格式
            const isValidFormat = this.validateResponseFormat(message);
            if (isValidFormat) {
              this.addTestResult('响应格式验证', true, '响应格式符合标准');
            } else {
              this.addTestResult('响应格式验证', false, '响应格式不符合标准');
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 解析响应失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('响应格式验证', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      // 发送请求
      const requestData = {
        c: 1339,
        d: { pageNum: 0 }
      };

      console.log(`📤 发送格式验证请求:`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      // 设置超时
      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('响应格式验证', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  async testPageSize () {
    console.log('\n📄 测试4: 分页大小验证（默认20条）');

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());

          if (message.act_id === 1339) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            // 验证分页大小
            if (message.code === 0 && Array.isArray(message.list)) {
              const listLength = message.list.length;
              if (listLength <= 20) {
                this.addTestResult('分页大小验证', true, `返回${listLength}条记录，符合默认20条限制`);
              } else {
                this.addTestResult('分页大小验证', false, `返回${listLength}条记录，超过默认20条限制`);
              }
            } else {
              this.addTestResult('分页大小验证', false, '响应格式错误');
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 解析响应失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('分页大小验证', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      // 发送请求
      const requestData = {
        c: 1339,
        d: { pageNum: 0 }
      };

      console.log(`📤 发送分页大小验证请求:`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      // 设置超时
      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('分页大小验证', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  validateResponseFormat (message) {
    // 验证基本结构
    if (!message.hasOwnProperty('act_id') || !message.hasOwnProperty('code')) {
      return false;
    }

    // 验证act_id
    if (message.act_id !== 1339) {
      return false;
    }

    // 验证code
    if (message.code !== 0) {
      return false;
    }

    // 验证list字段
    if (!message.hasOwnProperty('list') || !Array.isArray(message.list)) {
      return false;
    }

    // 验证list中的每个项目格式
    for (const item of message.list) {
      const requiredFields = ['creation_date', 'descr', 'game_id', 'gold', 'id', 'sliver', 'status', 'type'];
      for (const field of requiredFields) {
        if (!item.hasOwnProperty(field)) {
          return false;
        }
      }
    }

    return true;
  }

  async run () {
    try {
      await this.connect();
      await this.testStandardRequestFormat();
    } catch (error) {
      console.error('❌ 测试运行失败:', error);
    } finally {
      if (this.ws) {
        this.ws.close();
      }
    }
  }
}

// 运行测试
const tester = new Code1339StandardFormatTester();
tester.run(); 